package com.global.college.ui.activity;

import android.content.res.Configuration;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aliyun.player.IPlayer;
import com.aliyun.player.alivcplayerexpand.theme.Theme;
import com.aliyun.player.alivcplayerexpand.widget.AliyunVodPlayerView;
import com.aliyun.player.aliyunplayerbase.util.AliyunScreenMode;
import com.aliyun.player.source.VidAuth;
import com.bumptech.glide.Glide;
import com.global.college.MainActivity;
import com.global.college.R;
import com.global.college.UserData;
import com.global.college.base.BaseActivity;
import com.global.college.base.baselist.HsScrollViewPagerAdapter;
import com.global.college.data.net.CourseDetailBean;
import com.global.college.data.net.VideoDetailBean;
import com.global.college.data.net.VideoHistoryBean;
import com.global.college.ui.fragment.CourseDetailFragment;
import com.global.college.ui.fragment.training.CourseIntroFragment;
import com.global.college.ui.interfaces.ICourseDetailView;
import com.global.college.ui.presenter.CourseDetailPresenter;
import com.global.college.utils.StringUtils;
import com.global.college.widget.tab.SlidingTabLayout;
import com.global.college.widget.tab.listener.OnTabSelectListener;
import com.gyf.barlibrary.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 课程详情页
 *
 * @author: xjh
 * @datetime: 2021/12/6
 */
public class CourseDetailActivity extends BaseActivity implements ICourseDetailView {
    @BindView(R.id.mSlidingTab)
    SlidingTabLayout mSlidingTab;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.video_view)
    AliyunVodPlayerView mAliyunVodPlayerView;
    @BindView(R.id.btn_start_learn)
    TextView btnLearn;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.iv_image_bg)
    ImageView ivCover;

    private List<Fragment> mFragments = new ArrayList<>();
    private List<String> mTitles = new ArrayList<>();
    private int currentPosition = 1;

    private CourseDetailPresenter presenter;

    /**
     * 如果从训练营进入，则有训练营Id，用于记录视频历史
     */
    private String trainId;
    private String classId;

    private String mVideoId;

    private CourseDetailFragment courseDetailFragment;

    public boolean isBuy;//当前商品是否已购买
    public String goodId;//商品id

    private long timeStamp;//时间戳
    private long sumTime;//总时间

    private boolean isPlaying;

    @Override
    public int getContentViewId() {
        return R.layout.activity_course_detail;
    }

    /**
     * 不使用ImmersionBar 以满足沉浸式需求
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        useImmersionBar = false;
        setTheme(com.aliyun.vodplayer.R.style.NoActionTheme);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateNew(Bundle savedInstanceState) {
        setShowTitleBar(false);
        hideSystembar();

        ImmersionBar.with(CourseDetailActivity.this)
                .statusBarColor(R.color.transparent)
                .statusBarDarkFont(true)
                .init();//.hideB

        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        trainId = getIntent().getStringExtra("trainId");
        classId = getIntent().getStringExtra("classId");
        goodId = getIntent().getStringExtra("goodId");
        initAliyunPlayerView();
        presenter = new CourseDetailPresenter(this);
        presenter.setISelectView(this);
    }

    @Override
    public void getInitData() {
        presenter.initPlayerConfig(mAliyunVodPlayerView);
        setTabListener();
        if (StringUtils.isEmpty(goodId)) {
            //详情页或个人页进入，说明已购买，调我的课程详情接口
            presenter.getMyCourseDetail(classId);
        } else {
            //课程列表进入，调商品-课程详情接口
            presenter.getGoodsDetail(goodId);
        }
    }

    private void initAliyunPlayerView() {
        //保持屏幕敞亮
        mAliyunVodPlayerView.setKeepScreenOn(true);
        mAliyunVodPlayerView.setTheme(Theme.Blue);
        mAliyunVodPlayerView.setAutoPlay(true);
        mAliyunVodPlayerView.hideDanmakuView();
        setPlayerListener();
    }

    /**
     * 1、播放开始时计时、暂停/错误/进入后台时停止计时
     * 2、页面销毁、播放完成、切换视频时上报记录时间
     */
    private void setPlayerListener() {
        mAliyunVodPlayerView.setOnCompletionListener(new IPlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                saveHistoryAndReset();
            }
        });
        mAliyunVodPlayerView.setOnStateChangedListener(new IPlayer.OnStateChangedListener() {
            @Override
            public void onStateChanged(int i) {
                // TODO: 2022/1/26 changed
                Log.i(TAG, "onStateChanged:" + i);//3.开始 4.暂停 7.错误（停止）
                if (i == IPlayer.started) {
                    isPlaying = true;
                    timeStamp = System.currentTimeMillis();
                } else if (i == IPlayer.paused) {
                    isPlaying = false;
                    sumTime += System.currentTimeMillis() - timeStamp;
                } else if (i == IPlayer.error) {
                    isPlaying = false;
                    sumTime += System.currentTimeMillis() - timeStamp;
                }
            }
        });
    }

    /**
     * 记录播放时长并重置
     */
    private void saveHistoryAndReset() {
        if (isPlaying){
            sumTime += System.currentTimeMillis() - timeStamp;
        }
        if (sumTime == 0L){
            return;
        }
        presenter.saveVideoHistory(UserData.getInstance().getUserId(), mVideoId, trainId, classId, ((int) (sumTime / 1000)) + 1);
        isPlaying = false;
        timeStamp = 0L;
        sumTime = 0L;
    }

    /**
     * 获取视频记录
     */
    public void getVideoHistory(String videoId) {
        mVideoId = videoId;//设置默认视频id
        presenter.getVideoHistory(UserData.getInstance().getUserId(), trainId, classId);
    }

    private void setTabListener() {
        mSlidingTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
                currentPosition = position;
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setAutoPlay(false);
            mAliyunVodPlayerView.onStop();
        }
    }

    @Override
    protected void onDestroy() {
        if (mAliyunVodPlayerView != null) {
            saveHistoryAndReset();
            mAliyunVodPlayerView.onDestroy();
            mAliyunVodPlayerView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mAliyunVodPlayerView.mCurrentScreenMode == AliyunScreenMode.Full) {
            //设置为小屏状态
            mAliyunVodPlayerView.changeScreenMode(AliyunScreenMode.Small, false);
            return;
        }
        super.onBackPressed();
    }

    private void initTab(String courseIntro) {
        List<String> strs = new ArrayList<>();
        mTitles.add("简介");
        mTitles.add("目录");
        for (int i = 0; i < mTitles.size(); i++) {
            strs.add(mTitles.get(i));
        }
        mFragments.add(CourseIntroFragment.newInstance(courseIntro));
        courseDetailFragment = CourseDetailFragment.newInstance(classId, "");
        mFragments.add(courseDetailFragment);

        HsScrollViewPagerAdapter adapter = new HsScrollViewPagerAdapter(getSupportFragmentManager(), mFragments, strs);
        viewPager.setAdapter(adapter);
        mSlidingTab.setTabSpaceEqual(false);
        mSlidingTab.setViewPager(viewPager);
        viewPager.setCurrentItem(currentPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updatePlayerViewMode();
    }

    private void updatePlayerViewMode() {
        if (mAliyunVodPlayerView != null) {
            int orientation = getResources().getConfiguration().orientation;
//            if(mDownloadListTextView != null){
//                mDownloadListTextView.setVisibility(orientation == Configuration.ORIENTATION_PORTRAIT ? View.VISIBLE : View.GONE);
//            }
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

                //设置view的布局，宽高之类
                RelativeLayout.LayoutParams aliVcVideoViewLayoutParams = (RelativeLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = (int) (com.aliyun.player.aliyunplayerbase.util.ScreenUtils.getWidth(this) * 9.0f / 16);
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                //转到横屏了。
                //隐藏状态栏
                if (!isStrangePhone()) {
                    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
                }
                //设置view的布局，宽高
                RelativeLayout.LayoutParams aliVcVideoViewLayoutParams = (RelativeLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            }
        }
    }

    @OnClick({R.id.btn_start_learn, R.id.iv_play,R.id.line_start_learn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_play:
                getVideoAndPlay(mVideoId);
                break;
            case R.id.line_start_learn:
            case R.id.btn_start_learn:
                getVideoAndPlay(mVideoId);
                break;
            default:
                break;
        }
    }

    /**
     * 获取视频播放信息
     *
     * @param videoId
     */
    public void getVideoAndPlay(String videoId) {
        ivPlay.setVisibility(View.GONE);
        ivCover.setVisibility(View.GONE);
        if (!isBuy) {
            presenter.createOrder(UserData.getInstance().getUserId(), goodId);
            isBuy = true;
        }
        saveHistoryAndReset();
        mVideoId = videoId;
        presenter.getVideoDetail(videoId);
        mAliyunVodPlayerView.setAutoPlay(true);
    }

    @Override
    public void onGetVideoDetail(VideoDetailBean videoDetailBean) {
        VidAuth vidAuth = new VidAuth();
        vidAuth.setVid(mVideoId);//从app服务端获取此值
        vidAuth.setPlayAuth(videoDetailBean.getPlayAuth());//从app服务端获取此值
        vidAuth.setRegion("cn-shanghai");//默认为cn-shanghai。 可以咨询app服务端获取此值
        mAliyunVodPlayerView.setAuthInfo(vidAuth);//播放
        courseDetailFragment.setCurrentVideo(mVideoId);
    }

    @Override
    public void onGetVideoHistory(VideoHistoryBean videoHistoryBean) {
        if (!StringUtils.isEmpty(videoHistoryBean.getVideoId())) {
            mVideoId = videoHistoryBean.getVideoId();
            btnLearn.setText("继续学习");
        }
    }

    @Override
    public void onGetCourseDetail(CourseDetailBean bean) {
        initTab(bean.getClassNote());
        isBuy = bean.getGoodsBuy() == 1d;//1为已购买
        mAliyunVodPlayerView.setCoverUri(bean.getClassCover());
        Glide.with(this).load(bean.getClassCover()).into(ivCover);
    }
}
